public class StringConversion {
	// 09-03-2011 toHexString http://rgagnon.com/javadetails/java-0596.html
    // 09-03-2011 toByteArray && toLong
    // http://www.daniweb.com/software-development/java/code/216874

    public static final byte[] toByteArray(String hexString) {
        int arrLength = hexString.length() >> 1;
        byte buf[] = new byte[arrLength];

        for (int ii = 0; ii < arrLength; ii++) {
            int index = ii << 1;

            String l_digit = hexString.substring(index, index + 2);
            buf[ii] = (byte) Integer.parseInt(l_digit, 16);
        }

        return buf;
    }

    public static final byte[] toByteArray(long data) {
        /*
        return new byte[] { (byte) ((data >> 56) & 0xff),
                (byte) ((data >> 48) & 0xff), (byte) ((data >> 40) & 0xff),
                (byte) ((data >> 32) & 0xff), (byte) ((data >> 24) & 0xff),
                (byte) ((data >> 16) & 0xff), (byte) ((data >> 8) & 0xff),
                (byte) ((data >> 0) & 0xff), };*/
        byte b[] = new byte[8];
        for(int i=0; i<8; i++)
           b[i] = (byte)(data >>> (i * 8));
        return b;
    }

    public static final long toLong(byte[] data) {
        /*if (data == null || data.length != 8)
            return 0x0;
        // ----------
        return (long) (
        // (Below) convert to longs before shift because digits
        // are lost with ints beyond the 32-bit limit
        (long) (0xff & data[0]) << 56 | (long) (0xff & data[1]) << 48
                | (long) (0xff & data[2]) << 40 | (long) (0xff & data[3]) << 32
                | (long) (0xff & data[4]) << 24 | (long) (0xff & data[5]) << 16
                | (long) (0xff & data[6]) << 8 | (long) (0xff & data[7]) << 0);
        */
        long chunk = 0;
        for(int i=0; i<8; i++)
           chunk += ((data[i] & 0xFF) << (i * 8));
        return chunk;
    }

    private static final String HEXES = "0123456789abcdef";

    public static String toHexString(byte[] raw) {
        if (raw == null) {
            return null;
        }
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(
                    HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }

}
